//
//  NSURL+QL.m
//  QLSchool_IOS
//
//  Created by anan on 14-2-8.
//  Copyright (c) 2014年 baobaodev_anan. All rights reserved.
//

#import "NSURL+QL.h"

@implementation NSURL (QL)

+(NSURL *)ql_createURLWithParams:(NSString *)urlContentString params:(NSDictionary *)params
{
    NSMutableString *_tmpURLStr = [NSMutableString string];
    [_tmpURLStr appendString:urlContentString];
    NSRange _range = [urlContentString rangeOfString:@"?"];
    BOOL paramsFlat = NO;
    if (_range.location!=NSNotFound) {
        paramsFlat = YES;
    }
    if (params) {
        NSArray* _keys = [params allKeys];
        for (NSString *_key in _keys) {
            id value= [params objectForKey:_key];
            [_tmpURLStr appendFormat:@"%@%@=%@",(paramsFlat==YES?@"&":@"?"),_key,value];
            paramsFlat = YES;
        }
    }
    NSURL *_tempUrl = [NSURL URLWithString:[self formatStringToASCIIString:[_tmpURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    //NSLog(@"create url :%@ \n\n%@",_tempUrl.absoluteString,_tmpURLStr);
    return _tempUrl;
}

+(NSString *)formatStringToASCIIString:(NSString *)str
{
    if (!str) {
        return nil;
    }
    NSString *_tmp = [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    _tmp = [_tmp stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    const char * _tchar = [_tmp UTF8String];
    NSString *encodeStr = [NSString stringWithCString:_tchar encoding:NSASCIIStringEncoding];
    return encodeStr;
}

@end
